#include "learn.h"

int16_t count = 0;

_Noreturn void class_5_2()
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
    APB2_ENABLE(GPIOB, IPU, GPIO_Pin_0 | GPIO_Pin_1, 50MHz);

    //exti
    GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_Pin_1 | GPIO_Pin_0);
    EXTI_InitTypeDef exti_init = {
        .EXTI_Line = EXTI_Line0 | EXTI_Line1,
        .EXTI_Mode = EXTI_Mode_Interrupt,
        .EXTI_LineCmd = ENABLE,
        .EXTI_Trigger = EXTI_Trigger_Falling,
    };
    EXTI_Init(&exti_init);

    //nvic
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    NVIC_InitTypeDef nvic_Init = {
        .NVIC_IRQChannelCmd = ENABLE,
        .NVIC_IRQChannelSubPriority = 1,
        .NVIC_IRQChannelPreemptionPriority = 1,
    };

    nvic_Init.NVIC_IRQChannel = EXTI0_IRQn;
    NVIC_Init(&nvic_Init);

    nvic_Init.NVIC_IRQChannel = EXTI1_IRQn;
    nvic_Init.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_Init(&nvic_Init);

    OLED_Init();
    OLED_ShowString(1, 2, "Hello World");
    OLED_ShowString(2, 1, "Count:");
    while (1) {
        if (count >= 0) {
            OLED_ShowString(2, 7, "+");
            OLED_ShowNum(2, 8, count, 8);
        } else {
            OLED_ShowString(2, 7, "-");
            OLED_ShowNum(2, 8, -count, 8);
        }
    }
}

void EXTI0_IRQHandler()
{
    if (EXTI_GetITStatus(EXTI_Line0) == SET) {
        if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == RESET)
            count++;
        EXTI_ClearITPendingBit(EXTI_Line0);
    }
}

void EXTI1_IRQHandler()
{
    if (EXTI_GetITStatus(EXTI_Line1) == SET) {
        if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == RESET)
            count--;
        EXTI_ClearITPendingBit(EXTI_Line1);
    }
}
